package com.frkj.yuan.fragment.order;

import android.app.Dialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.frkj.yuan.R;
import com.frkj.yuan.activity.AgainYuYueJiuzhenPersonActivity;
import com.frkj.yuan.activity.ServiceAccoMpanyingActivity;
import com.frkj.yuan.activity.UserLoginActivity;
import com.frkj.yuan.adapter.BaseRecyclerHolder;
import com.frkj.yuan.adapter.BaseRecyclerRefreshAdapter;
import com.frkj.yuan.api.bean.OrderMsgBean;
import com.frkj.yuan.api.bean.OrderPayorderMsgBean;
import com.frkj.yuan.api.category.OrderMsgCategory;
import com.frkj.yuan.api.presenter.OrderListPresenter;
import com.frkj.yuan.base.BaseBean;
import com.frkj.yuan.base.BaseFragment;
import com.frkj.yuan.dialog.LoadingDialog;
import com.frkj.yuan.dialog.LoginOutDialog;
import com.frkj.yuan.dialog.OnQuiteDialogClickListener;
import com.frkj.yuan.dialog.RoundCornerDialog;
import com.frkj.yuan.main.ConstantStaticUrl;
import com.frkj.yuan.utils.HttpNetworkConnectUtils;
import com.frkj.yuan.utils.SPUtils;
import com.frkj.yuan.utils.ToastUtil;
import com.frkj.yuan.view.RecyclerViewLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static android.content.Context.MODE_PRIVATE;

/**
 * 作者：菲菲 on 2022/2/17 11:20
 * company：丰蓉信息科技有限公司
 */
public class FuwuZhongFragment extends BaseFragment implements OrderMsgCategory.View, OnRefreshListener {
    @BindView(R.id.base_refresh_recycler)
    RecyclerView mRecyclerViews;
    private OrderListPresenter mPresenter;
    private long mUserId;
    private String mToken;
    private int pageNumber = 1;
    @BindView(R.id.base_refresh)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.relat_empty)
    RelativeLayout mRelatEmpty;
    private List<OrderMsgBean.OrderMsgBeanData.OrderMsgBeanDataList> mlist = new ArrayList<>();
    private BaseRecyclerRefreshAdapter<OrderMsgBean.OrderMsgBeanData.OrderMsgBeanDataList> mAdapter;
    private boolean isLoading = false;
    private JSONObject result;
    private LoadingDialog mpcd;
    private LoginOutDialog dialog;
    @Override
    public void onResume() {
        super.onResume();
        smartRefreshLayout.autoRefresh();
    }
    // TODO: 2022/6/8 fragment 来回切换自动刷新列表数据
    @Override
    public void onHiddenChanged(boolean hidden) {
        // TODO Auto-generated method stub
        super.onHiddenChanged(hidden);
        if (!hidden) {
            smartRefreshLayout.autoRefresh();
        }
    }
    @Override
    public int getLayoutResource() {
        return R.layout.base_refresh_recycler_view;
    }
    @Override
    public void initLayoutView() {
        mpcd = new LoadingDialog(getActivity());
        mpcd.show();
        RecyclerViewLayoutManager.setLinearVerticalManager(getActivity(),mRecyclerViews);
        mToken = (String) SPUtils.get(getActivity(), ConstantStaticUrl.mToken, "");
        RecyclerViewLayoutManager.setLinearVerticalManager(getActivity(), mRecyclerViews);
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("First", MODE_PRIVATE);
        mUserId = sharedPreferences.getLong(ConstantStaticUrl.userId, 0);
        mAdapter = new BaseRecyclerRefreshAdapter<OrderMsgBean.OrderMsgBeanData.OrderMsgBeanDataList>(getActivity(),  R.layout.service_zhong_view) {
            @Override
            public void convert(BaseRecyclerHolder holder, OrderMsgBean.OrderMsgBeanData.OrderMsgBeanDataList item, int position, boolean isScrolling) throws IOException {
                holder.setText(R.id.obl_title, "订单号 : " + item.getOrderNo());
                holder.setText(R.id.obl_msg, "医院 : " + item.getOrderDTO().getHospitalName());
                holder.setText(R.id.order_keshi_service, "科室 : " + item.getOrderDTO().getOfficeName());
                holder.setText(R.id.order_xiagnm, item.getOrderDTO().getServiceName());
                holder.setText(R.id.fuw_time,item.getOrderDTO().getPeriodStr());
                holder.setText(R.id.orer_xingm,item.getOrderDTO().getPatientName());
                DecimalFormat format = new DecimalFormat("0.00");
                holder.setText(R.id.order_price, "￥" +format.format(item.getOrderDTO().getPrice()));

                holder.getView(R.id.ckjc_server).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("yiyuan",mlist.get(position).getOrderDTO().getHospitalName());
                        bundle.putString("keshi",mlist.get(position).getOrderDTO().getOfficeName());
                        bundle.putString("xiangm",mlist.get(position).getOrderDTO().getServiceName());
                        bundle.putString("jiuzhenren",mlist.get(position).getOrderDTO().getPatientName());
                        bundle.putString("shijian",mlist.get(position).getOrderDTO().getPeriodStr());
                        openActivityWitchAnimation(ServiceAccoMpanyingActivity.class,bundle);
                    }
                });
                holder.getView(R.id.service_xudan).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        RoundCornerDialog dialog = new RoundCornerDialog(getActivity(), "确定再次预约吗？","确定","取消", new OnQuiteDialogClickListener() {
                            @Override
                            public void onConfirm(Dialog dialog) {
                                Bundle bundle = new Bundle();
                                bundle.putLong("orderId",mlist.get(position).getId());
                                openActivityWitchAnimation(AgainYuYueJiuzhenPersonActivity.class,bundle);
                                dialog.dismiss();
                            }
                            @Override
                            public void onCancel(Dialog dialog) {
                                dialog.dismiss();
                            }
                        });
                        dialog.show();
                    }
                });

            }
        };
        mAdapter.setDatas(mlist);
        mRecyclerViews.setAdapter(mAdapter);
        mPresenter = new OrderListPresenter(this);
        SetPersenter(mPresenter);
        result = new JSONObject();
        try {
            result.put("userId", mUserId);
            result.put("orderStatus", 4);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (!HttpNetworkConnectUtils.isNetworkConnected(getActivity())) {
            ToastUtil.showToastERROR(getActivity(), "网络不给力,请稍后重试");
        } else {
            mPresenter.getOrderList(pageNumber, mToken, result.toString());
        }
        smartRefreshLayout.setOnRefreshListener(this);

    }
    @Override
    public void getOrderList(OrderMsgBean orderMsgBean) {
        if (orderMsgBean.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            if (orderMsgBean.getData() != null && orderMsgBean.getData().getList().size() > 0) {
                if (pageNumber == 1) {
                    if (isLoading) {
                        isLoading = false;
                    } else {
                        mlist.clear();
                    }
                    mlist.addAll(orderMsgBean.getData().getList());
                    mAdapter.setDatas(orderMsgBean.getData().getList());
                } else {
                    mlist.addAll(mlist.size(), orderMsgBean.getData().getList());
                    mAdapter.add(orderMsgBean.getData().getList());
                }
                mRelatEmpty.setVisibility(View.GONE);
                mRecyclerViews.setVisibility(View.VISIBLE);
            } else {
                if (isLoading) {
                    isLoading = false;
                }else {
                    mRelatEmpty.setVisibility(View.VISIBLE);
                    mRecyclerViews.setVisibility(View.GONE);
                }
            }
        }else if (orderMsgBean.getCode()==401){
            if (dialog == null){
                dialog = new LoginOutDialog(getActivity());
            }
            if(dialog != null  && !dialog.isShowing()){
                dialog.show();
            }
            dialog.findViewById(R.id.circler_delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.findViewById(R.id.to_login).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openActivityWitchAnimation(UserLoginActivity.class);
                    SPUtils.clear(getActivity());
                    getActivity().finish();
                    dialog.dismiss();
                }
            });
        }else {
            ToastUtil.showToastERROR(getActivity(),orderMsgBean.getMsg());
        }
        mpcd.dismiss();
    }
    @Override
    public void getPayOrderMsg(OrderPayorderMsgBean payorderMsgBean) {
    }
    @Override
    public void getCancle(BaseBean payOrderNoBean) {
    }

    @Override
    public void getTuikuanMoney(BaseBean payOrderNoBean) {

    }

    @Override
    public void SetPersenter(Object persenter) {

    }
    @Override
    public void OnShowErrorMsg(String mErrorMsg) {
        mpcd.dismiss();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNumber = 1;
        mPresenter.getOrderList(pageNumber, mToken, result.toString());
        smartRefreshLayout.finishRefresh(500);
    }
}
